<?php

namespace App\Admin\Annotation\Parser;

use App\Admin\Middleware\PermissionMiddleware;
use Newbie\Annotation\Contracts\IAnnotationParser;
use Newbie\Annotation\Parser\RouteAnnotationParser;

class AnnotationPermissionParser implements IAnnotationParser
{

    /**
     * 处理注解
     * @access public
     * @param array $item
     * @return void
     */
    public static function process(array $item): void
    {
        if ($item['type'] === 'class') {
            self::handleClassAnnotation($item['class']);
        } else if ($item['type'] === 'method') {
            self::handleMethodAnnotation($item, $item['class']);
        }
    }

    /**
     * 处理类注解
     * @access public
     * @param string $className
     * @return void
     */
    public static function handleClassAnnotation(string $className): void
    {
        $param = [
            'middlewares' => [PermissionMiddleware::class],
            'only' => [],
            'except' => [],
        ];
        RouteAnnotationParser::bindClassMidllewares($className, $param);
    }

    /**
     * 处理方法注解
     * @access public
     * @param array $item
     * @param string $className
     * @return void
     */
    public static function handleMethodAnnotation(array $item, string $className): void
    {
        $method = $item['method'];
        RouteAnnotationParser::bindMethodMidllewares($className, $method, [PermissionMiddleware::class]);
        RouteAnnotationParser::bindRouteParam($className, $method, ['permission' => $item['parameters']['name']] ?? '');
    }
}